import router from "@/router";
import { useUserStoreHook } from "@/store/modules/user";
// import { usePermissionStoreHook } from "@/store/modules/permission";
import { message } from "ant-design-vue";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false }); // 进度条

// const permissionStore = usePermissionStoreHook();

// 白名单路由
const whiteList = ["/login",'/dashboard'];
export function setupPermission() {
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const hasToken = sessionStorage.getItem("accessToken");
    console.log("hasToken:", hasToken);
    if (hasToken) {
      console.log("hasToken11111:", hasToken);
      if (to.path === "/login") {
        // 如果已登录，跳转首页
        next({ path: "/dashboard" });
        NProgress.done();
      } else {
        next(); //放行当前的导航请求
      }
      // else {
      //   const userStore = useUserStoreHook();
      //   const hasRoles = userStore.roles && userStore.roles.length > 0;
      //   if (hasRoles) {
      //     next();
      //   }
      //  else {
      // 登录后获取用户信息，获取路由
      //   try {
      //     await userStore.getInfo();
      //     userStore.getConfigKey();
      //     const accessRoutes = await permissionStore.generateRoutes();
      //     if (accessRoutes.length) {
      //       accessRoutes.forEach((route) => {
      //         router.addRoute("MainPage", route);
      //       });
      //       next({ path: to.path, query: to.query });
      //     } else {
      //       message.warning("请联系管理员分配菜单权限！");
      //       await userStore.resetToken();
      //       next("/login");
      //       NProgress.done();
      //     }
      //   } catch (error) {
      //     console.log(error);
      //     // 移除 token 并跳转登录页
      //     await userStore.resetToken();
      //     next(`/login?redirect=${to.fullPath}`);
      //     NProgress.done();
      //   }
      // }
      // }
    } else {
      console.log("未登录");
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1) {
        console.log("白名单");

        next();
      } else {
        console.log("未登录,非白名单");

        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });
}
